package com.yc.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.cloud.admin.dto.request.AvatarsCreateParam;
import com.yc.cloud.admin.dto.request.AvatarsUpdateParam;
import com.yc.cloud.admin.service.AvatarsService;
import com.yc.cloud.admin.service.AvatarsSettingService;
import com.yc.cloud.admin.vo.AvatarsVo;
import com.yc.cloud.basic.dto.BaseQueryParam;
import com.yc.cloud.entity.Avatars;
import com.yc.cloud.entity.AvatarsSetting;
import com.yc.cloud.mapper.AvatarsMapper;
import com.yc.cloud.oss.service.OssFileService;
import com.yc.cloud.security.utils.AdminUtils;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数字人形象 服务实现类
 * </p>
 *
 * @author Yancy
 * @since 2024-03-10
 */
@Service
public class AvatarsServiceImpl extends ServiceImpl<AvatarsMapper, Avatars> implements AvatarsService {

    private final OssFileService ossFileService;
    private final AvatarsSettingService avatarsSettingService;

    public AvatarsServiceImpl(OssFileService ossFileService, AvatarsSettingService avatarsSettingService) {
        this.ossFileService = ossFileService;
        this.avatarsSettingService = avatarsSettingService;
    }

    @Override
    public IPage<AvatarsVo> list(BaseQueryParam queryParam) {
        val query = new QueryWrapper<Avatars>();
        IPage<Avatars> page;
        query.and(avatarsQueryWrapper -> {
            avatarsQueryWrapper.eq(Avatars.COMPANY_ID, AdminUtils.getCurrentCompanyId()).or().eq(Avatars.COMPANY_ID, 0L);
        });
        //排序
        if (StrUtil.isNotEmpty(queryParam.getSortBy())) {
            if (BaseQueryParam.ORDER_DESC.equals(queryParam.getOrder())) {
                query.orderByDesc(queryParam.getSortBy());
            } else if (BaseQueryParam.ORDER_ASC.equals(queryParam.getOrder())) {
                query.orderByAsc(queryParam.getSortBy());
            }
        }
        //模糊查询
//        if (StrUtil.isNotEmpty(queryParam.getKeyword())) {
//            query.and(queryWrapper -> {
//
//            });
//        }
        //分页
        if (queryParam.getPage()) {
            page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize(), true);
        } else {
            page = new Page<>(queryParam.getPageNum(), baseMapper.selectCount(query), true);
        }
        val result = baseMapper.selectPage(page, query);
        return result.convert(this::convertVo);
    }

    @Override
    @Transactional
    public Avatars create(AvatarsCreateParam param) {
        val avatars = new Avatars();
        BeanUtils.copyProperties(param, avatars);
        //如果不开放,则将数字人信息设置企业ID做数据隔离
        if (param.getOpen() == null || !param.getOpen()) {
            avatars.setCompanyId(AdminUtils.getCurrentCompanyId());
        } else {
            avatars.setCompanyId(0L);
        }
        val saveFlag = save(avatars);
        if (saveFlag) {
            val avatarsSetting = new AvatarsSetting();
            avatarsSetting.setAvatarId(avatars.getId());
            avatarsSetting.setCompanyId(AdminUtils.getCurrentCompanyId());
            avatarsSetting.setWakeUpAudios(param.getWakeUpAudios());
            avatarsSettingService.save(avatarsSetting);
        }
        return saveFlag ? avatars : null;
    }

    @Override
    public Avatars get(Long id) {
        return getById(id);
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    @Transactional
    public Avatars update(Long id, AvatarsUpdateParam param) {
        val avatars = new Avatars();
        BeanUtils.copyProperties(param, avatars);
        avatars.setId(id);
        val currentCompanyId = AdminUtils.getCurrentCompanyId();
        //如果不开放,则将数字人信息设置企业ID做数据隔离
//        if (param.getOpen() == null || !param.getOpen()) {
//            avatars.setCompanyId(currentCompanyId);
//        } else {
//            avatars.setCompanyId(0L);
//        }
        val updateFlag = updateById(avatars);
        if (updateFlag) {
            var settings = avatarsSettingService.getByCompanyIdAndAvatarId(currentCompanyId, id);
            if (settings == null) {
                settings = new AvatarsSetting();
            }
            settings.setAvatarId(id);
            settings.setCompanyId(currentCompanyId);
            settings.setWakeUpAudios(param.getWakeUpAudios());
            avatarsSettingService.saveOrUpdate(settings);
        }
        return updateFlag ? avatars : null;
    }


    @Override
    public AvatarsVo convertVo(Avatars avatars) {
        if (avatars == null) {
            return null;
        }
        val vo = new AvatarsVo();
        BeanUtils.copyProperties(avatars, vo);
        vo.setUrl(ossFileService.getOssFileUrl(String.valueOf(vo.getFileId())));
        vo.setLowUrl(ossFileService.getOssFileUrl(String.valueOf(vo.getLowFileId())));
        vo.setCoverUrl(ossFileService.getOssFileUrl(String.valueOf(vo.getCover())));
        //唤醒动作
        if (StrUtil.isNotEmpty(avatars.getWakeupAnimationsName())) {
            val wakeupAnimationsNameArray = avatars.getWakeupAnimationsName().split(",");
            vo.setWakeUpAnimationsNameList(Arrays.asList(wakeupAnimationsNameArray));
        }
        //去settings里查看设置信息
        val settings = avatarsSettingService.getByCompanyIdAndAvatarId(AdminUtils.getCurrentCompanyId(), avatars.getId());
        if (settings != null) {
            val wakeUpAudios = settings.getWakeUpAudios();
            if (StrUtil.isNotEmpty(wakeUpAudios)) {
                //string转 list<Long>
                val wakeUpAudiosList = Arrays.asList(wakeUpAudios.split(","));
                val wakeUpAudiosOssFileList = ossFileService.listByFileIds(wakeUpAudiosList);
               // vo.setWakeUpAudioList(wakeUpAudiosOssFileList);
            }
        }
        return vo;
    }

    @Override
    public List<AvatarsVo> convertVo(List<Avatars> AvatarsList) {
        if (CollUtil.isNotEmpty(AvatarsList)) {
            return AvatarsList.stream().map(this::convertVo).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
